package com.zkj.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zkj.constant.MessageConstant;
import com.zkj.dto.UserLoginDTO;
import com.zkj.entity.User;
import com.zkj.exception.EmployeeNotLoginException;
import com.zkj.mapper.UserMapper;
import com.zkj.properties.WechatProperties;
import com.zkj.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zkj.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author zkj
 * @since 2024-08-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private static final String WX_LOGINURL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WechatProperties wechatProperties;

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String jsCode = wechatLogin(userLoginDTO.getCode());
        log.info("jsCode:{}", jsCode);

        LambdaQueryWrapper<User> query = new LambdaQueryWrapper<>();
        query.eq(User::getOpenid, jsCode);

        User user = userMapper.selectOne(query);
        // 判断是否有该用户
        if (user == null) {
            // 没有则创建
            user = new User();
            user.setOpenid(jsCode);
            userMapper.insert(user);
        }

        return user;
    }

    // 微信请求
    private String wechatLogin(String jsCode) {

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", wechatProperties.getAppid());
        paramMap.put("secret", wechatProperties.getSecret());
        paramMap.put("js_code", jsCode);
        paramMap.put("grant_type", "authorization_code");
        String responseStr = HttpClientUtil.doGet(WX_LOGINURL, paramMap);
        log.info("微信登录响应：{}", responseStr);

        JSONObject parseObj = JSONObject.parseObject(responseStr);
        String openid = parseObj.getString("openid");

        // 判断openid
        if (openid == null) {
            throw new EmployeeNotLoginException(MessageConstant.WX_LOGIN_ERR);
        }
        return openid;
    }

}
